<template>
    <div>
        <!-- 日期选择 -->
        <div class="min-w-[540px]">
            <el-form class="flex flex-wrap lg:justify-start sm:justify-center py-4 pl-4 bg-white border border-sky-100">
                <el-form-item label="标签名称">
                    <el-input v-model="searchTagName" placeholder="请输入" style="width: 200px;" />
                </el-form-item>
                <el-form-item label="创建日期" class="ml-4">
                    <!-- 日期选择组件（区间选择） -->
                    <el-date-picker v-model="pickDate" @change="datepickerChange" :shotcuts="shortcuts" type="daterange"
                        range-separator="至" start-placeholder="Start Time" end-placeholder="End Time" size="default" />
                </el-form-item>
                <el-button type="primary" :icon="Search" class="ml-4" @click="onSubmit">查询</el-button>
                <el-button class="ml-4" :icon="RefreshRight" @click="onReset">重置</el-button>
            </el-form>
        </div>
        <!-- 标签列表 -->
        <div class="mt-4 bg-white border border-sky-100 pt-4 min-w-[540px]">
            <!-- 新增按钮 -->
            <div class="mb-4 pl-4">
                <el-button type="primary" @click="showAddTagDialog">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>
                    新增</el-button>
            </div>
            <!-- 表格 -->
            <el-table class="ml-4" :data="tableData" border stripe style="width: 90%; min-width: 520px;" max-height="550" v-loading="tableLoading">
                <el-table-column prop="name" label="标签名称" width="180">
                    <template #default="scope">
                        <el-popover effect="light" trigger="hover" placement="top" width="auto">
                            <template #default>
                                <div>{{ scope.row.name }}</div>
                            </template>
                            <template #reference>
                                <el-tag type="success">{{ scope.row.name }}</el-tag>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作" >
                    <template #default="scope">
                        <div class="flex flex-nowrap">
                            <el-button @click="toEdit(scope.row)" type="primary" size="small">
                            <el-icon class="mr-1">
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button @click="toDelete(scope.row)" type="danger" size="small">
                            <el-icon class="mr-1">
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="mt-10 mb-4 flex justify-center w-full">
                <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20]"
                    @size-change="pageSizeChange" @current-change="currentPageChange" :small="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" class="" />
            </div>
        </div>


        <!-- 新增标签对话框 -->
        <FormDialog ref="formDialogRef" title="新增标签" @submit="addTag" @cancle="handleCancle" confirm-text="新增">
            <div class="text-red-500 text-sm">标签格式: 非空,1~15位:数字,大小写字母,汉字,和'_'</div>
            <el-form ref="formRef" :model="formValue">
                <el-form-item label="标签:" label-width="80px" size="large">
                    <div class="flex gap-2 flex-wrap w-full">
                        <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false"
                            @close="handleClose(tag)">
                            {{ tag }}
                        </el-tag>
                        <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                            @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                        <el-button v-else class="button-new-tag" size="default" @click="showInput">
                            + New Tag
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
        </FormDialog>

        <!-- 修改标签对话框 -->
        <FormDialog ref="editFormDialogRef" title="修改标签" @submit="editTag" @cancle="handleCancle" confirm-text="修改">
            <!-- 3项: tagName, updateTime(不能改),  -->
            <div class="text-red-500 text-sm mb-2 pl-2">标签格式: 非空,1~10位:数字,大小写字母,汉字,和'_'</div>
            <el-form ref="editFormRef" :model="editFormValue">
                <el-form-item label="标签名称:" label-width="80px" size="default">
                    <el-input v-model="editFormValue.name" />
                </el-form-item>
                <div class="text-gray-400 text-sm my-2 h-[20px]">
                    <span class="float-right">LastUpdateTime: {{ editFormValue.updateTime }}</span>
                </div>
            </el-form>
            
        </FormDialog>


    </div>
</template>

<script setup>
import { Search, RefreshRight } from '@element-plus/icons-vue';
import { showConfirm, showMessage } from '@/composables/utils';
import { ref, reactive, onBeforeMount, nextTick } from 'vue';
import moment from 'moment';
import { deleteTag, getTagPageList, addTagList, getTagById, updateTag } from '@/api/admin/tag';
import FormDialog from '@/components/FormDialog.vue';
//====================== 日期选择事件 ======================
const startDate = reactive({})
const endDate = reactive({})
const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')
    console.log('startTime:' + startDate.value + 'endTime:' + endDate.value)
}
//日期shotscut
const shortcuts = [
    {
        text: 'Today',
        value: new Date(),
    },
    {
        text: 'Yesterday',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            return [start, end];
        },
    },
    {
        text: 'A week ago',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
];


// 查询的标签名称
const searchTagName = ref('');
// 日期(过滤条件)
const pickDate = ref('');
//表格数据
const tableData = ref([])
//========================分页数据========================
// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(5)
//提交查询标签事件
//loading
const tableLoading = ref(false)
const onSubmit = () => {    //显示表格 loading
    tableLoading.value = true
    getTagPageList({
        name: searchTagName.value,
        startDate: startDate.value,
        endDate: endDate.value,
        current: current.value,
        size: size.value
    }).then(res => {
        if (res.success) {
            tableData.value = res.data
            total.value = res.total
            current.value = res.current
            size.value = res.size
        }
    }).finally(() => {
        tableLoading.value = false
    })
}
// 进入页面的时候获取一次数据
onBeforeMount(() => {
    onSubmit()
})
// 页码改变事件
const currentPageChange = (val) => {
    console.log("当前页码: " + val)
    current.value = val
    onSubmit()
}
// 页码大小改变事件
const pageSizeChange = (val) => {
    console.log("当前页码大小: " + val)
    size.value = val
    onSubmit()
}
const onReset = () => {     //重置查询条件
    searchTagName.value = ''
    pickDate.value = '' //视图
    startDate.value = ''    //提交数据
    endDate.value = ''
    size.value = 5
    current.value = 1
}
//======================新增标签==========================
//1.添加要新增的标签
const InputRef = ref(null)  //输入框实例
const dynamicTags = ref([])    //动态标签
const inputVisible = ref(false) //标签输入框
const inputValue = ref('')
const handleClose = (tag) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}
const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value?.input?.focus()
    })
}
const handleInputConfirm = () => {
    //表单校验
    if(!/^[\u4e00-\u9fa5a-zA-Z0-9_]{1,15}$/.test(inputValue.value)){  //不满足
        showMessage('标签格式: 非空,1~15位:数字,大小写字母,汉字,和_', 'error')
        return
    }
    dynamicTags.value.push(inputValue.value)
    inputVisible.value = false
    inputValue.value = ''
}
//2.向后端发起请求, 新增标签
//表单校验部分
const formRef = ref(null)
const formValue = reactive({
    tags: []
})
const formDialogRef = ref(null)
const showAddTagDialog = () => {
    formDialogRef.value.showDialog()
}
const addTag = () => {
    console.log(/^[\u4e00-\u9fa5a-zA-Z0-9_]{1,15}$/.test(inputValue.value))
    //表单校验
    dynamicTags.value.forEach(item => {
        if(!/^[\u4e00-\u9fa5a-zA-Z0-9_]{1,15}$/.test(item)){  //不满足
            showMessage('标签格式: 非空,1~15位:数字,大小写字母,汉字,和_', 'error')
            return
        }
    })
    formValue.tags = dynamicTags.value
    //发起异步请求
    addTagList(formValue).then((res) => {
        if (res.success == true) {
            showMessage('新增标签成功！', 'success')
            formDialogRef.value.closeDialog()   //关闭弹窗
            //置空
            formValue.tags = []
            dynamicTags.value = []
            onSubmit()  //刷新表格
        } else {
            let message = res.message
            showMessage(message, 'error')    //错误提示
        }
    })
}
//3.取消新增
const handleCancle = () => {  // input填写内容清空
    inputValue.value = ''
}


//======================删除标签==========================
const toDelete = (row) => {
    //弹出确认confirm
    showConfirm('确定要删除该标签吗').then(() => {
        //发起异步请求
        deleteTag(row.id).then((res) => {
            if (res.success == true) {
                showMessage('删除成功！', 'success')
                onSubmit()
            } else {
                let message = res.message
                showMessage(message, 'error')
            }
        })
    }).catch(() => {

    })
}
//======================编辑标签==========================
const editFormDialogRef = ref(null) //获取编辑标签对话框实例
const editFormRef = ref(null) //获取编辑标签表单实例
const editFormValue = reactive({
    id: '',
    name: '',
    updateTime: ''
})
const toEdit = (row) => {
    //展示编辑标签对话框
    editFormDialogRef.value.showDialog()
    //发送get请求, 获取数据, 赋值给editFormValue
    getTagById(row.id).then((res) => {
        if (res.success == true) {
            editFormValue.id = res.data.id
            editFormValue.name = res.data.name
            editFormValue.updateTime = res.data.updateTime
        }
    }).catch((err) => {
        showMessage(err, 'error')
    })
}
const editTag = ()=>{   //确认编辑
    //表单校验
    if(!/^[\u4e00-\u9fa5a-zA-Z0-9_]{1,15}$/.test(editFormValue.name)){  //不满足
        showMessage('标签格式: 非空,1~15位:数字,大小写字母,汉字,和_', 'error')
        return
    }
    //提交修改
    updateTag(editFormValue).then((res) => {
        if (res.success == true) {
            showMessage('修改标签成功！', 'success')
            editFormDialogRef.value.closeDialog()   //关闭弹窗
            onSubmit()  //刷新表格
        } else {
            let message = res.message
            showMessage(message, 'error')    //错误提示
        }
    }).catch((err) => {
        showMessage(err, 'error')
    })

}










</script>

<style scoped>
.el-form-item {
    margin-bottom: 0;
}
</style>